import os, random, json
from django.conf import settings
from django_filters.rest_framework import DjangoFilterBackend
from django.http import JsonResponse

from rest_framework import serializers
from rest_framework import fields
from rest_framework.serializers import *
from rest_framework.parsers import FormParser, MultiPartParser, JSONParser
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator  # 验证器

from mysqldb.models import *

# from allinpay import apidev as PAY
# from mysqldb.models import *
# from mysqldb import redis as REDIS


def has_Random(l=6):
    """返回随机数"""
    s = ""
    for i in range(l):
        s += str(random.choice(range(9)))
    return s


class ListDjangoFilterBackend(DjangoFilterBackend):
    """自己定义过滤器"""

    def get_schema_fields(self, view):
        if view.action not in ["list"]:
            return []
        return super().get_schema_fields(view)


class NoneSerializer(serializers.Serializer):
    """无序列化"""

    class Meta:
        fields = "__all__"


class SemsMsgSerializer(serializers.Serializer):
    """短信请求序列化"""

    username = CharField(max_length=255, required=True, help_text="用户名(手机、邮箱或openid)")
    act = ChoiceField(["SEMS", "EMAIL"], required=True, help_text="验证方式(短信、邮件)")

    class Meta:
        fields = "__all__"


class SemsVerifSerializer(serializers.Serializer):
    """验证短信"""

    username = CharField(max_length=255, required=True, help_text="用户名(手机、邮箱或openid)")
    password = CharField(max_length=255, required=True, help_text="验证码")

    class Meta:
        fields = "__all__"


class AllinpaySysAttrSerializer(serializers.Serializer):
    """网站属性配置 1"""

    name = CharField(max_length=255, help_text="配置名称")
    logo = CharField(max_length=255, help_text="Logo上传")
    width = IntegerField(help_text="logo宽")
    height = IntegerField(help_text="logo高")
    icp = CharField(max_length=255, help_text="ICP备案号")
    callme = CharField(max_length=255, help_text="联系方式")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpaySecretkeyListSerializer(serializers.Serializer):
    """密钥列表 2"""

    name = CharField(max_length=255, help_text="配置名称")
    appid = CharField(max_length=255, help_text="应用软件ID")
    shopid = CharField(
        max_length=255,
        help_text="商户ID",
    )
    bnkpublic = CharField(
        help_text="银行公钥",
        style={"base_template": "textarea.html"},
    )
    rsaprivate = CharField(
        help_text="rsa私钥",
        style={"base_template": "textarea.html"},
    )
    rsapublic = CharField(
        help_text="rsa公钥",
        style={"base_template": "textarea.html"},
    )
    interface = CharField(
        max_length=255,
        help_text="接口请求地址",
    )
    notify = CharField(
        max_length=255,
        help_text="消息通知地址",
    )
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"

    # def validate_bnkpublic(self, attr):
    #     if not PAY.checkRsaKey(attr):
    #         raise serializers.ValidationError({"bnkpublic": "银行公钥无效"})
    #     return attr

    # def validate_rsapublic(self, attr):
    #     if not PAY.checkRsaKey(attr):
    #         raise serializers.ValidationError({"rsapublic": "RSA公钥无效"})
    #     return attr

    # def validate_rsaprivate(self, attr):
    #     if not PAY.checkRsaKey(attr):
    #         raise serializers.ValidationError({"rsaprivate": "RSA私钥无效"})
    #     return attr

    # def validate_interface(self, attr):
    #     if not attr[-1] == "/":
    #         attr += "/"
    #     if not PAY.checkUrl(attr):
    #         raise serializers.ValidationError({"interface": "请求页面不可到达"})
    #     return attr

    # def validate_notify(self, attr):
    #     if not attr[-1] == "/":
    #         attr += "/"
    #     if not PAY.checkUrl(attr):
    #         raise serializers.ValidationError({"notify": "通知页面不可到达"})
    #     return attr


class AllinpaySysSemsSerializer(serializers.Serializer):
    """短信网关配置 3"""

    name = CharField(max_length=255, help_text="配置名称")
    signname = CharField(max_length=255, help_text="短信签名")
    secretid = CharField(max_length=255, help_text="secretid")
    secretkey = CharField(max_length=255, help_text="secretkey")
    sessdkappid = CharField(max_length=255, help_text="appid")
    templateid = CharField(max_length=255, help_text="短信模板id")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpaySysMailSerializer(serializers.Serializer):
    """邮箱配置 4"""

    name = CharField(max_length=255, required=True, help_text="配置名称")
    username = CharField(max_length=255, required=True, help_text="发件人")
    password = CharField(max_length=255, required=True, help_text="授权码")
    pop3 = CharField(max_length=255, required=True, help_text="服务器地址")
    title = CharField(max_length=255, required=True, help_text="邮件标题")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpaySysSumSerializer(serializers.Serializer):
    """结算数据配置 5"""

    min_value = IntegerField(min_value=0, default=0, help_text="最小结算金额(分)")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpaySysPaySerializer(serializers.Serializer):
    """分账接口数据配置 6"""

    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")
    ipaddr = CharField(max_length=255, required=False, help_text="银行前置网关")
    port = IntegerField(min_value=0, default=0, help_text="端口")
    bank = CharField(max_length=255, required=True, help_text="开户行")
    card = CharField(max_length=255, required=True, help_text="卡号")
    name = CharField(max_length=255, required=True, help_text="户名")
    addr = CharField(max_length=255, required=True, help_text="银行地址")
    code = CharField(max_length=255, required=True, help_text="联行号")
    idcode = CharField(max_length=255, required=True, help_text="客户号")

    class Meta:
        fields = "__all__"


class AllinpayAlertSerializer(serializers.Serializer):
    """语音参数"""

    name = CharField(max_length=255, required=True, help_text="名称")
    host = CharField(max_length=255, required=True, help_text="地址")
    user = CharField(max_length=255, required=True, help_text="凭证ID")
    key = CharField(max_length=255, required=True, help_text="凭证KEY")
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpayWeChatSerializer(serializers.Serializer):
    """微信参数配置"""

    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="名称",
    )
    host = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="api接口地址",
    )
    appid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="小程序 appId",
    )
    secret = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="小程序 appSecret",
    )
    weappid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="公众号 appId",
    )
    wesecret = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="公众号 appSecret",
    )
    status = IntegerField(min_value=0, max_value=1, required=True, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpayPlsarSerializer(serializers.Serializer):
    """消息队列参数配置"""

    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="名称",
    )
    host = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="api接口地址(不带请求头)",
    )
    pport = CharField(
        allow_blank=True, allow_null=True, required=True, help_text="业务端口"
    )
    wport = CharField(
        allow_blank=True, allow_null=True, required=True, help_text="管理端口"
    )
    namespace = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="命名空间",
    )

    status = IntegerField(min_value=0, max_value=1, required=True, help_text="状态")

    class Meta:
        fields = "__all__"


class AllinpayPulsarTopicSerializer(serializers.Serializer):
    """主题信息"""

    namespaces = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="命名空间(tiktok,yisbar)",
    )
    topic = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=True,
        help_text="订阅主题(code_pchost)",
    )

    class Meta:
        fields = "__all__"


class UpdateImagesSerializer(serializers.Serializer):
    """上传图片, 需要安装Pillow包"""

    files = ImageField(
        max_length=None, allow_empty_file=False, use_url=False, help_text="图片文件"
    )
    type = CharField(help_text="来源类型")

    class Meta:
        fields = ("files", "type")


class UpdateFilesSerializer(serializers.Serializer):
    """上传文件, 需要安装Pillow包"""

    files = FileField(
        max_length=None, allow_empty_file=False, use_url=False, help_text="ROM文件"
    )
    type = CharField(help_text="来源类型")

    class Meta:
        fields = ("files", "type")


class UpdateSoftSerializer(serializers.Serializer):
    """上传文件, 需要安装Pillow包"""

    files = FileField(
        max_length=None, allow_empty_file=False, use_url=False, help_text="文件"
    )
    type = CharField(help_text="来源类型")

    class Meta:
        fields = ("files", "type")


class GlobalConfIntegralListSerializer(serializers.ModelSerializer):
    """全局积分类型列表"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        help_text="名称",
        validators=[UniqueValidator(queryset=AllinpayIntegralList.objects.all())],
    )
    status = IntegerField(max_value=1, min_value=0, default=0, help_text="状态")
    total = IntegerField(max_value=1, min_value=0, default=0, help_text="是否累计(只加不减)")

    class Meta:
        model = AllinpayIntegralList
        fields = "__all__"


class GlobalWorkitemModelSerializer(serializers.ModelSerializer):
    """全局工作项模板"""

    id = IntegerField(label="ID", read_only=True)
    types = IntegerField(default=1, min_value=1, help_text="类型")
    title = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="标题")
    ismoon = fields.MultipleChoiceField(
        choices=list(range(1, 32)),
        required=False,
        help_text="月工作日([1-31])",
    )
    isweek = fields.MultipleChoiceField(
        choices=list(range(7)), required=False, help_text="周工作日([0-6])"
    )
    examples = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="照片",
    )
    content = CharField(
        allow_blank=True,
        allow_null=True,
        required=False,
        help_text="工作内容",
        style={"base_template": "textarea.html"},
    )
    star = TimeField(allow_null=True, help_text="开始时间")
    over = TimeField(allow_null=True, help_text="结束时间")
    alarm = TimeField(allow_null=True, help_text="提醒时间")
    submit = TimeField(allow_null=True, help_text="提交时间")
    autodelivery = IntegerField(default=0, max_value=1, min_value=0, help_text="是否自动分配")
    autodraw = IntegerField(default=0, max_value=1, min_value=0, help_text="是否自动接单")
    gradeappoint = IntegerField(default=0, max_value=1, min_value=0, help_text="按排班分配")
    jobappoint = IntegerField(default=0, max_value=1, min_value=0, help_text="按岗位分配")
    camera = IntegerField(default=0, max_value=1, min_value=0, help_text="抓拍")
    integral = IntegerField(default=0, max_value=1, min_value=0, help_text="奖励积分类型")
    status = IntegerField(default=0, max_value=1, min_value=0, help_text="状态")

    class Meta:
        model = AllinpayWorkitemModel
        fields = "__all__"

    def validate(self, attrs):
        sess = attrs.copy()
        ismoon = sess.get("ismoon")
        isweek = sess.get("isweek")
        if not len(ismoon):
            sess.pop("ismoon")
        if not len(isweek):
            sess.pop("isweek")
        return sess

    def to_representation(self, instance):
        """mysql to python"""
        ret = super().to_representation(instance)
        if ret["ismoon"]:
            ret["ismoon"] = [x for x in ret["ismoon"] if type(x) == int]
        if ret["isweek"]:
            ret["isweek"] = [x for x in ret["isweek"] if type(x) == int]
        return ret


# class DjangoCeleryBeatPeriodictaskSerializer(serializers.ModelSerializer):
#     """计划任务"""

#     crontab = PrimaryKeyRelatedField(
#         allow_null=True,
#         queryset=DjangoCeleryBeatCrontabschedule.objects.all(),
#         required=False,
#     )
#     interval = PrimaryKeyRelatedField(
#         allow_null=True,
#         queryset=DjangoCeleryBeatIntervalschedule.objects.all(),
#         required=False,
#     )
#     solar = PrimaryKeyRelatedField(
#         allow_null=True,
#         queryset=DjangoCeleryBeatSolarschedule.objects.all(),
#         required=False,
#     )
#     clocked = PrimaryKeyRelatedField(
#         allow_null=True,
#         queryset=DjangoCeleryBeatClockedschedule.objects.all(),
#         required=False,
#     )

#     class Meta:
#         model = DjangoCeleryBeatPeriodictask
#         fields = "__all__"


# class DjangoCeleryBeatCrontabscheduleSerializer(serializers.ModelSerializer):
#     """计划任务"""

#     id = IntegerField(label="ID", read_only=True)
#     minute = CharField(max_length=240)
#     hour = CharField(max_length=96)
#     day_of_week = CharField(max_length=64)
#     day_of_month = CharField(max_length=124)
#     month_of_year = CharField(max_length=64)
#     timezone = CharField(max_length=63)

#     class Meta:
#         model = DjangoCeleryBeatCrontabschedule
#         fields = "__all__"


# class DjangoCeleryBeatIntervalscheduleSerializer(serializers.ModelSerializer):
#     """无序列化"""

#     id = IntegerField(label="ID", read_only=True)
#     every = IntegerField(max_value=2147483647, min_value=-2147483648)
#     period = CharField(max_length=24)

#     class Meta:
#         model = DjangoCeleryBeatIntervalschedule
#         fields = "__all__"


# class DjangoCeleryBeatSolarscheduleSerializer(serializers.ModelSerializer):
#     """无序列化"""

#     id = IntegerField(label="ID", read_only=True)
#     event = CharField(max_length=24, required=True)
#     latitude = DecimalField(decimal_places=6, max_digits=9, required=True)
#     longitude = DecimalField(decimal_places=6, max_digits=9, required=True)

#     class Meta:
#         model = DjangoCeleryBeatSolarschedule
#         fields = "__all__"


# class DjangoCeleryBeatClockedscheduleSerializer(serializers.ModelSerializer):
#     """无序列化"""

#     id = IntegerField(label="ID", read_only=True)
#     clocked_time = DateTimeField()

#     class Meta:
#         model = DjangoCeleryBeatClockedschedule
#         fields = "__all__"


class CeleryTaskResSerializer(serializers.Serializer):
    """无序列化"""

    celeryID = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="任务ID"
    )

    class Meta:
        fields = "__all__"


class FileUploadSerializer(serializers.Serializer):
    """无序列化"""

    barcode = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="场所ID"
    )
    hostname = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="计算机名"
    )
    gamename = CharField(
        allow_blank=True, allow_null=True, max_length=255, help_text="游戏名"
    )
    ontime = DateTimeField(default=timezone.now)

    class Meta:
        fields = "__all__"


class MainVersionListSerializer(serializers.ModelSerializer):
    """场所端版本"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(help_text="场所ID")
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="描述字符串",
    )

    class Meta:
        model = MainVersionList
        fields = "__all__"


class TestCreateWorkItemsSerializer(serializers.Serializer):
    """手动创建工作项"""

    wid = IntegerField(required=False, help_text="模板ID")
    pid = IntegerField(required=False, help_text="场所ID")
    sid = IntegerField(required=False, help_text="员工ID")
    day = DateField(required=False, help_text="事务日期")

    class Meta:
        fields = "__all__"


class GamoPlacetokenListSerializer(serializers.ModelSerializer):
    """注册三方授权"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="描述字符串",
    )
    status = IntegerField(min_value=0, max_value=1, default=0, help_text="状态")
    appid = ReadOnlyField()
    secret = ReadOnlyField()
    outdate = ReadOnlyField()
    lasted = ReadOnlyField()
    created = ReadOnlyField()

    class Meta:
        model = GamoPlacetokenList
        fields = "__all__"


class GamoPlacetokenLoginSerializer(serializers.Serializer):
    """登录三方授权"""

    appid = CharField(help_text="appid")
    secret = CharField(help_text="secret")

    class Meta:
        fields = "__all__"


class AllinpayAuthViewsSerializer(serializers.ModelSerializer):
    """视图列表序列化"""

    class Meta:
        model = AllinpayAuthViews
        fields = "__all__"


# print(repr(MainVersionListSerializer()))
